<?php
require_once 'base.php';
require_once APPPATH . '/libraries/ZLib/File/GDImage.php';

class Products extends Base {
	
	public function __construct() {
		parent::__construct();
		$this->lang->load('products');
	}
	
	public function add() {
		$this->load->model('product_model');
		
		$categories = $this->product_model->get_categories();
		$new_categories = array();
		
		foreach ($categories as $category) {
			$new_categories[$category['id']] = $category['name'];
		}
		
		$this->set_variable('categories', $new_categories);
		
		if (Console::isDebugEnabled()) {
			Console::var_dump($new_categories);
		}
		
		$this->render('add');
	}
	
	public function do_add() {
		if (!$this->validate_add_form()) {
			return $this->redirect('/products/add');
		}
		
		$this->load->model('product_model');
		$product_id = $this->product_model->save(array(
				'name' => trim($this->get_param('name')),
				'category_id' => $this->get_param('category'),
				'comment' => trim($this->get_param('comment')),
				'user_id' => Security_Manager::get_visitor()->id));
		
		if (!(boolean) $product_id) {
			$this->add_error_message('Could not save the product');
			return $this->redirect('/products/add');
		}
		
		if (!mkdir(APPPATH .'../storage/products/'. $product_id)) {
			$this->product_model->remove();
			$this->add_error_message('Could not create product storage folder');
			return $this->redirect('/products/add');
		}
		
		$this->load->library('upload', array(
				'upload_path' => APPPATH .'../storage/products/'
					. $product_id .'/',
				'allowed_types' => 'jpg|png',
				'remove_spaces' => true));
		
		$upload_error = false;
		$success_added = array();
		
		if (Console::isDebugEnabled()) {
			Console::var_dump($_FILES);
		}
		
		foreach ($_FILES as $key => $file) {
			if (!$this->upload->do_upload($key)) {
				$error = array('error' => $this->upload->display_errors());
				$this->add_error_message($error['error']);
				$upload_error = true;
				break;
			}
			
			$data = $this->upload->data();
			
			if (!$this->process_uploaded_image($data)) {
				$upload_error = true;
				break;
			}
			
			$success_added[] = $data;
		}
		
		if (Console::isDebugEnabled()) {
			Console::debug('Is upload error: '. $upload_error);
			Console::debug('Success count: '. count($success_added));
			Console::var_dump($success_added);
		}
		
		if ($upload_error) {
			foreach ($success_added as $item) {
				@unlink($item['full_path']);
			}
			
			$this->product_model->remove($product_id);
			$this->add_error_message('The images could not be added. The 
				object is not save');
			return $this->redirect('/products/add');
		} else {
			foreach ($success_added as $item) {
				$this->product_model
					->save_image($product_id, $item['file_name']);
			}
		}
		
		$this->add_success_message('Object added successefully');
		return $this->redirect('/products/view/'. $product_id);
	}
	
	public function do_add_comment() {
		$id = $this->get_param('id');
		$comment = $this->get_param('comment');
		
		$this->load->model('product_model');
		
		if (!$this->product_model->exist($id)) {
			return $this->redirect('/');
		}
		
		if ($this->product_model->save_comment(
				Security_Manager::get_visitor()->get_id(),
				$id, $comment)) {
			$this->add_success_message('Comment added successful!');
		} else {
			$this->add_error_message('Error on adding cmment!');
		}
		
		return $this->redirect('/products/view/'. $id);
	}
	
	public function index() {
		$this->redirect('/products/viewall/latest');
	}
	
	public function view($id) {
		$this->load->library('calendar');
		$this->load->model('product_model');
		$this->load->model('user_model');
		
		$product = $this->product_model->get($id);
		
		if (Console::isDebugEnabled()) {
			Console::var_dump($product);
		}
		
		$this->set_variable('product', $product);
		$this->set_variable('images', $this->product_model->get_images($id));
		$this->set_variable('owner', $this->user_model->get($product['user_id']));
		$this->set_variable('comments', $this->product_model->get_comments($id));
		$this->render('view');
	}
	
	public function viewAll($order='latest', $page = 0) {
		$this->load->model('product_model');
		
		$products = $this->product_model->get_products($order, $page, 20);
		$this->set_variable('products', $products);
		
		if (Console::isDebugEnabled()) {
			Console::var_dump($products);
		}
		
		$this->set_variable('order', $order);
		
		$this->render('viewall');
	}
	
	public function valid_category($str) {
		if (!defined('__form_validation__')) {
			return $this->redirect('/errors/error_404');
		}
		
		$this->form_validation->set_message(
				'valid_category', 'Invalid category');
		
		return is_numeric($str);
	}
	
	public function validate_name($str) {
		if (!defined('__form_validation__')) {
			return $this->redirect('/errors/error_404');
		}
		
		$this->form_validation->set_message('valid_category', 'Invalid name');
		return (bool) preg_match('/^([\w\s]+)$/i', $str);
	}
	
	private function validate_add_form() {
		define('__form_validation__', true);
		$this->form_validation->set_rules(
				'name', 'Name object', 'required|callback_validate_name');
		$this->form_validation->set_rules(
				'category', 'Category', 'required|callback_valid_category');
		return $this->form_validation->run();
	}
	
	private function process_uploaded_image($image_data) {
		$image = new ZLib_File_GDImage($image_data['full_path']);
		$sizes = $this->config->item('image_sizes');
		
		foreach ($sizes as $key => $size) {
			$image->scaleByMax($size);
			$image->dump($image_data['file_path'] . $key .'-'. $image_data['file_name']);
		}
		
		return true;
	}
}